package leedcode_path.Link;


import java.sql.PreparedStatement;

public class MyLinkedList {
    int size;
//    虚拟头结点
    ListNode dummyhead;

    public MyLinkedList() {
        size=0;
        dummyhead=new ListNode(0);
    }

    public int get(int index) {
        if(index<0||index>size-1) return -1;
        ListNode cur=dummyhead.next;
        while (index!=0){
            cur=cur.next;
            index--;
        }
        return cur.val;
    }

    public void addAtHead(int val) {
        ListNode newhead=new ListNode(val);
        newhead.next=dummyhead.next;
        dummyhead.next=newhead;
        size++;
    }

    public void addAtTail(int val) {
        ListNode newTail=new ListNode(val);
        ListNode cur=dummyhead;
        while (cur.next!=null){
            cur=cur.next;
        }
        cur.next=newTail;
        newTail.next=null;
        size++;
    }

    public void addAtIndex(int index, int val) {
        ListNode newnode=new ListNode(val);
        ListNode cur=dummyhead;
        if(index>size) return;
            while (index!=0){
                cur=cur.next;
                index--;
            }
            newnode.next=cur.next;
            cur.next=newnode;
            size++;



    }

    public void deleteAtIndex(int index) {
        if(index < 0 || index >= size) return ;
        ListNode cur=dummyhead;
        while (index!=0){
            cur=cur.next;
            index--;
        }
        cur.next=cur.next.next;
        size--;

    }

    public static void main(String[] args) {
        MyLinkedList myLinkedList = new MyLinkedList();
        myLinkedList.addAtHead(1);
        myLinkedList.addAtTail(3);
        myLinkedList.addAtIndex(3, 2);    // 链表变为 1->2->3

    }
}


